package com.zd.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//从内存中读取认证信息
                .passwordEncoder(new BCryptPasswordEncoder())//设置密码加密器
                .withUser("admin")//自定义用户名
                .password(new BCryptPasswordEncoder().encode("admin"))//自定义密码
                .roles("admin");//权限
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/index/**","/logout")//放行的资源
                .permitAll()//所有人都可以访问
                .anyRequest()
                .authenticated()
                .and()//开始其他的配置
                .formLogin()//自定义表单登录
                .loginPage("/")//设置登录页面
                .loginProcessingUrl("/login")//表单提交URL
                .usernameParameter("uname")//自定义用户名-默认：username
                .passwordParameter("upwd")//自定义用户密码-默认：password
                .defaultSuccessUrl("/news/list")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl("/")//退出成功回到首页
                .deleteCookies("JSESSIONID")
                .permitAll()


        ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/images/**", "/js/**");
    }
}
